package com.fourth.config;

import com.fourth.dto.Result;
import com.fourth.enums.ResultCode;
import com.fourth.util.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 * @author 邓建波
 */
@Slf4j
@ControllerAdvice
public class WebExceptionAdvice {
    @ExceptionHandler(RuntimeException.class)
    public Result handleRuntimeException(RuntimeException e, HttpServletRequest request){
        // TODO 1.记录错误
        log.error("url:{}, msg:{}",request.getRequestURL(),e.getMessage());
        //TODO 2.判断异常
        if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            // TODO 2.1 封装返回业务错误
            return  Result.builder().code(businessException.getCode())
                    .message(businessException.getMessage())
                    .build();
        } else {
            // TODO 2.2 返回未知错误
            return new Result(ResultCode.UN_KNOWN);
        }
    }
}
